// var urls = {
//   api: 'https://api.xizengkeji.com/',
//   wechat: 'https://wechat.xizengkeji.com/',
//   live: 'https://live.xizengkeji.com/',
//   store: 'https://store.xizengkeji.com/'
// }
var urls = {
  api: 'https://api.rootphp.com/',
  wechat: 'https://wechat.rootphp.com/',
  store: 'https://store.rootphp.com/',
  live: 'https://live.rootphp.com/'
}
const md5 = require('../utils/md5.js');

function link(url, data, rep, method, fail, urlType) {
  var _this = this
  if (data == undefined) {
    data = {}
  }
  if (!method) {
    method = "POST"
  }
  wx.request({
    url: urls[urlType ? urlType : 'api'] + url,
    method: method,
    data: data,
    header: getHeader(data, url, urlType ? urlType : 'api'),
    success: function (res) {
      console.log('接口返回数据res:',{"接口名称：" : urls[urlType ? urlType : "api"] + url,'接口状态':res.data.code,'接口返回数据：':res})
      if (res.data.msg == "缺少Token参数" || res.data.msg == "Token验证失败") {
        var pages = getCurrentPages();
        var that = pages.length >= 2 ? pages[pages.length - 1] : pages[0];
        console.log(that)
        if (that.route != 'pages/Login/Index/index' && that.route != 'tabbarPage/News/News/News' && that.route != 'pages/onNewPages/onLiveInfopage/onLiveInfopage') {
          wx.navigateTo({
            url: '/pages/Login/Index/index',
          })
        }
      }
      try {
        rep(res);
      } catch (err) {
        var pages = getCurrentPages();
        var that = pages.length >= 2 ? pages[pages.length - 1] : pages[0];
        if (that.route != 'pages/Login/Index/index' && that.route != 'tabbarPage/News/News/News' && that.route != 'pages/onNewPages/onLiveInfopage/onLiveInfopage') {
          console.log(err)
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
      if (res.data.code == 201) {
        _this.sync()
      }
    },
    fail: function (res) {
      console.log(res)
      fail(res);
      console.log('接口请求失败，该方法执行清除本地所有缓存')
      console.log(getHeader(data, url))
    },
  })
}
/**
 * token失效跳转首页方法
 */
module.exports.filaModal = function () {
  wx.showModal({
    content: '登录信息已失效，请重新登陆',
    showCancel: false,
    success: (result) => {
      if (result.confirm) {
        wx.removeStorageSync('token')
        wx.removeStorageSync('store')
        wx.reLaunch({
          url: '/pages/onNewPages/dreamBrightness_loginGuide/loginGuide',
        })
      }
    },
    title: '温馨提示',
  })
}
/**
 * 201刷新后台缓存数据
 */
module.exports.sync = function () {
  this.link('syncData', {
    is_sync: 1
  }, function (rep) {
    console.log('刷新缓存成功', rep)
    wx.setStorageSync('member', rep.data.data)
    if (rep.data.code == 200) {
      if (rep.data.data.member_info != undefined) {
        wx.setStorageSync('renzheng', 1)
      }
    }
  })
}
//请求封装
function getHeader(data, url, urlType) {
  const timestamp = Date.parse(new Date()) / 1000
  const obj = {
    timestamp: timestamp,
    domain: urls[urlType ? urlType : 'api'],
    key: 'XIZENGB7D0C9D279892857DE5490AB856772FE',
    pathinfo: url
  }
  try {
    console.log('加密的data数据---', JSON.parse(data.client_data))
    var string = JSON.parse(data.client_data),
      strings = JSON.parse(string.rawData)
    strings.nickName = 'AA'
    string.rawData = JSON.stringify(strings)
    string.userInfo.nickName = 'AA'
    data.client_data = JSON.stringify(string)
    console.log(data)
  } catch (error) {

  }
  if (data) {
    var sign_obj = objKeySort({
      ...obj,
      ...data,
    })
  } else {
    var sign_obj = objKeySort({
      ...obj,
    })
  }
  const sign_Arr = [];
  for (let i in sign_obj) {
    sign_Arr.push((i + '=' + sign_obj[i]))
  }
  var string = sign_Arr.join("&")
  console.log('sign-----', string)
  console.log('Md5------', md5.md5(string))
  const sign_Last = md5.md5(string).toLowerCase()
  if (wx.getStorageSync('token')) {
    var header = {
      'sign': sign_Last,
      'token': wx.getStorageSync('token'),
      'timestamp': timestamp,
      // 'debug': 'true'
    }
  } else {
    var header = {
      'sign': sign_Last,
      'token': '',
      'timestamp': timestamp,
      // 'debug': 'true'
    }
  }
  if (url == 'v1/bindMobile') {}
  // header.Cookie= 'PHPSESSID=' +wx.getStorageSync('session') + '; path=/; HttpOnly'
  header.Cookie = 'PHPSESSID=42d26dafc5c8f2c40963b0e6be5b7626; path=/'
  return header
}

function objKeySort(obj) {
  var newkey = Object.keys(obj).sort();
  var newObj = {};
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = obj[newkey[i]];
  }
  return newObj;
}

function toast(title, icon) {
  wx.showToast({
    title: title,
    icon: icon
  })
}
//setTimeout方法
function outTime(time, fun) {
  setTimeout(() => {
    fun()
  }, time)
}

function toalert(title, t, imgtype) {
  var errimgsrc = '';
  if (t == undefined) {
    t = 3000;
  }
  if (imgtype == undefined) {
    errimgsrc = '/images/gantaohao.png';
  }
  wx.showToast({
    title: title,
    icon: 'success',
    image: errimgsrc,
    duration: t
  })
}

function log(rep) {
  console.log(JSON.parse(rep))
}
/**
 * 获取或设置页面data
 */
module.exports.data = function (n, json) {
  var pages = getCurrentPages();
  var that = pages.length >= 2 ? pages[pages.length - 1] : pages[0];
  if (typeof n == 'object') {
    that.setData(n);
    return false;
  } else {
    if (typeof json == 'object') {
      for (var item in json) {
        that.data[n][item] = json[item];
      }
      that.setData(n);
    }
  }
  return that.data[n];
}
/**
 * 隐藏弹窗
 */
module.exports.hid = function () {
  wx.hideToast()
}
/**
 * 获取页面路径
 */
module.exports.NetPageIP = function (PageIP, e) {
  let page = '',
    parameter = e ? e : ''
  var app = getApp();
  console.log('app——---', app)
  for (let i in app.NetPageIP) {
    if (i == PageIP) {
      page = app.NetPageIP[i] + parameter
    }
  }
  if (!page) {
    _this.toast('地址填写错误', 'none')
    return false
  }
  console.log('传过来的页面数据', PageIP, e)
  console.log('跳转页面', page)
  return page
}
/**
 * 页面跳转
 */
module.exports.PageRoter = function (url, e, type) {
  console.log('传过来的页面链接', url)
  if (type == 'nav') {
    wx.navigateTo({
      url: this.NetPageIP(url, e)
    })
  }
  if (type == 'red') {
    wx.redirectTo({
      url: this.NetPageIP(url, e)
    })
  }
  if (type == 'rel') {
    wx.reLaunch({
      url: this.NetPageIP(url, e)
    })
  }
  if (type == 'swi') {
    wx.switchTab({
      url: this.NetPageIP(url, e)
    })
  }
}
module.exports.formatNumber = function (n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
module.exports.formatTime = function (number, format) {
  var that = this
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(that.formatNumber(date.getMonth() + 1));
  returnArr.push(that.formatNumber(date.getDate()));

  returnArr.push(that.formatNumber(date.getHours()));
  returnArr.push(that.formatNumber(date.getMinutes()));
  returnArr.push(that.formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
module.exports.log = log
module.exports.link = link
module.exports.toast = toast
module.exports.toalert = toalert
module.exports.outTime = outTime